{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Definition for a binary tree node.\n",
    "# class TreeNode(object):\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.left = None\n",
    "#         self.right = None\n",
    "\n",
    "class Solution(object):\n",
    "    def lowestCommonAncestor(self, root, p, q):\n",
    "        \"\"\"\n",
    "        :type root: TreeNode\n",
    "        :type p: TreeNode\n",
    "        :type q: TreeNode\n",
    "        :rtype: TreeNode\n",
    "        \"\"\"\n",
    "        p_ancestor = []\n",
    "        q_ancestor = []\n",
    "        def findNode(node, val, ancestor):\n",
    "            if node is None:\n",
    "                return False\n",
    "            if node.val == val:\n",
    "                ancestor.append(node)\n",
    "                return True\n",
    "            \n",
    "            if findNode(node.left, val, ancestor) or findNode(node.right, val, ancestor):\n",
    "                ancestor.append(node)\n",
    "                return True\n",
    "            else:\n",
    "                return False\n",
    "                \n",
    "        findNode(root, p.val, p_ancestor)\n",
    "        findNode(root, q.val, q_ancestor)\n",
    "        \n",
    "        p_ancestor = p_ancestor[::-1]\n",
    "        q_ancestor = q_ancestor[::-1]\n",
    "        \n",
    "        # Ignore root which must be LCA\n",
    "        i = 1\n",
    "        while i < len(p_ancestor) and i < len(q_ancestor) :\n",
    "            if p_ancestor[i].val == q_ancestor[i].val:\n",
    "                i = i + 1\n",
    "            else:\n",
    "                break\n",
    "        \n",
    "        return p_ancestor[i-1]"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
